package springboot.study.project.service.impl;

import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import springboot.study.project.constant.SessionConstant;
import springboot.study.project.dto.UserDto;
import springboot.study.project.mapper.UserMapper;
import springboot.study.project.model.User;
import springboot.study.project.model.UserExample;
import springboot.study.project.service.UserService;
import springboot.study.project.util.common.CookieUtil;
import springboot.study.project.util.common.SessionUtil;
import springboot.study.project.util.common.StringUtil;
import springboot.study.project.util.common.Util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @ClassName: UserServiceImpl
 * @Description: 用户服务接口实现类
 * @Author: liu-hao
 * @Date: 2021-03-04 22:59
 * @Version: 1.0
 **/
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public int login(String userName, String userPwd, String role, String isRememberPwd, HttpServletRequest request, HttpServletResponse response) {
        int status = 0;
        UserExample userExample = new UserExample();
        userExample.createCriteria().andUserNameEqualTo(userName).andRoleEqualTo(role);
        List<User> adminList = userMapper.selectByExample(userExample);
        if (adminList.size() <= 0) {
            status = -1; // 用户不存在
        } else {
            UserExample userExample2 = new UserExample();
            userExample2.createCriteria().andUserNameEqualTo(userName).andPasswordEqualTo(userPwd);
            List<User> adminList2 = userMapper.selectByExample(userExample2);
            if (adminList2.size() <= 0) {
                status = -2; // 用户登录校验失败，密码不正确
            } else {
                User user = adminList2.get(0);
                // 生成新的Token(登录令牌)
                String newToken = UUID.randomUUID().toString();
                user.setToken(newToken);
                int updateCount = userMapper.updateByPrimaryKey(user);
                if (updateCount > 0) {
                    // 设置Session
                    HttpSession session = request.getSession();
                    session.setAttribute("user", user);
                    //SessionUtil.setSessionAttribute("user", user);
                    // 设置Cookies
                    CookieUtil.setCookie(response, "userId", user.getId() + "", 60 * 30);
                    CookieUtil.setCookie(response, "token", newToken, 60 * 30);
                    CookieUtil.setCookie(response, "userRealName", user.getRealName());
                    CookieUtil.setCookie(response, "userName", user.getUserName());
                    CookieUtil.setCookie(response, "role", user.getRole());
                    if (StringUtil.isNotBlank(role) && "1".equals(isRememberPwd)) {
                        CookieUtil.setCookie(response, "userPwd", user.getPassword());
                    }
                }
                status = user.getId(); // 登录校验成功，返回学生编码
            }
        }
        return status;
    }

    @Override
    public void logout(String userId, HttpServletRequest request, HttpServletResponse response) {
        // 清除session
        SessionUtil.removeSessionAttribute("user");
        // 清cookies
        CookieUtil.setCookie(response, "token", "", 0);
    }

    @Override
    public boolean addUser(User user) {
        if (user == null || StringUtil.isBlank(user.getUserName()))
            return false;
        String userName = user.getUserName();
        UserExample example = new UserExample();
        example.createCriteria().andUserNameEqualTo(userName);
        int count = userMapper.countByExample(example);
        if (count == 0) {
            user.setGmtCreate(System.currentTimeMillis());
            user.setGmtModify(user.getGmtCreate());
            int insertCount = userMapper.insert(user);
            return insertCount > 0 ? true : false;
        }
        return false;
    }

    @Override
    public boolean modifyUserInfo(User user) {
        if (user != null && StringUtil.isNotBlank(user.getId())) {
            user.setGmtModify(System.currentTimeMillis());
            int updateCount = userMapper.updateByPrimaryKeySelective(user);
            return updateCount > 0 ? true : false;
        }
        return false;
    }

    @Override
    public boolean removeUser(String userId) {
        if (StringUtil.isNotBlank(userId)) {
            int deleteCount = userMapper.deleteByPrimaryKey(Util.getIntOfObj(userId));
            return deleteCount > 0 ? true : false;
        }
        return false;
    }

    @Override
    public boolean banUser(String userId) {
        return false;
    }

    @Override
    public User findUserByToken(String token) {
        UserExample example = new UserExample();
        example.createCriteria().andTokenEqualTo(token);
        List<User> users = userMapper.selectByExample(example);
        if (users != null && users.size() > 0) {
            return users.get(0);
        }
        return null;
    }

    @Override
    public User findUserById(String userId) {
        if (StringUtil.isNotBlank(userId)) {
            User user = userMapper.selectByPrimaryKey(Util.getIntOfObj(userId));
            return user;
        }
        return null;
    }

    @Override
    public Map<String, Object> findUser(String userName, String realName, String role, int offset, int pageSize) {
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        if (StringUtil.isNotBlank(userName)) {
            criteria.andUserNameLike("%" + userName + "%");
        }
        if (StringUtil.isNotBlank(realName)) {
            criteria.andRealNameLike("%" + realName + "%");
        }
        if (StringUtil.isNotBlank(role)) {
            criteria.andRoleEqualTo(role);
        }
        // 查询符合条件公告数量
        int totalCount = userMapper.countByExample(example);
        // 查询符合条件的公告信息
        List<User> users = userMapper.selectByExampleWithRowbounds(example, new RowBounds(offset, pageSize));
        List<UserDto> userDtos = new ArrayList<>();
        for (User user : users) {
            UserDto userDto = new UserDto();
            BeanUtils.copyProperties(user, userDto);
            if ("1".equals(user.getRole())) {
                userDto.setRoleStr("超级管理员");
            } else if ("2".equals(user.getRole())) {
                userDto.setRoleStr("老师");
            } else if ("3".equals(user.getRole())) {
                userDto.setRoleStr("宿舍管理员");
            } else if ("4".equals(user.getRole())) {
                userDto.setRoleStr("学生");
            }
            userDtos.add(userDto);
        }
        // 定义返回Map
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", 0);
        resultMap.put("msg", 0);
        resultMap.put("count", totalCount);
        resultMap.put("data", userDtos);
        return resultMap;
    }
}
